package com.xiaobai.spike.web.oauth2;

import com.xiaobai.spike.entity.User;
import com.xiaobai.spike.model.request.AuthRequest;
import com.xiaobai.spike.model.request.TokenRequest;
import com.xiaobai.spike.model.response.TokenResponse;
import com.xiaobai.spike.sdk.lang.ApiResponse;
import com.xiaobai.spike.service.client.OauthClientDetailsService;
import com.xiaobai.spike.service.oauth2.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/oauth2")
public class AuthController {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private OauthClientDetailsService oauthClientDetailsService;

    @Resource
    private AuthService authService;

    @PostMapping("/authorize")
    public ApiResponse<String> authorize(@Validated @RequestBody AuthRequest authRequest) {
        return ApiResponse.success(authService.authorizeCode(authRequest));
    }

    @PostMapping("/getToken")
    public ApiResponse<TokenResponse> token(@Validated @RequestBody TokenRequest tokenRequest) {
        TokenResponse tokenResponse = authService.authorizeToken(tokenRequest);
//        String params = OkHttpUtil.postJsonParams(tokenRequest.getRedirect_uri(), JSON.toJSONString(tokenResponse));
        return ApiResponse.success(tokenResponse);
    }

    @PostMapping("/getByToken")
    public ApiResponse<User> getByToken(@RequestParam("access_token") String access_token) {
        System.out.println(access_token);
        return ApiResponse.success(authService.getByToken(access_token));
    }

    @PostMapping("/refreshToken")
    public ApiResponse<TokenResponse> refreshToken(@RequestParam("refresh_token") String refresh_token) {
        return ApiResponse.success(authService.refreshToken(refresh_token));
    }

    @PostMapping("/invalidAccessToken")
    public ApiResponse<Integer> invalidAccessToken(@RequestParam("access_token") String access_token) {
        return ApiResponse.success(authService.invalidAccessToken(access_token));
    }

    @PostMapping("/invalidRefreshToken")
    public ApiResponse<Integer> invalidRefreshToken(@RequestParam("refresh_token") String refresh_token) {
        return ApiResponse.success(authService.invalidRefreshToken(refresh_token));
    }

}
